<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RoleRealm - 对话</title>
    <link rel="stylesheet" href="/css/style.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'PingFang SC', 'Inter', sans-serif; background: #f1f5f9; height: 100vh; display: flex; flex-direction: column; }
        .chat-header { background: white; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); padding: 15px 20px; display: flex; justify-content: space-between; align-items: center; z-index: 100; }
        .character-info { display: flex; align-items: center; gap: 15px; }
        .character-avatar { width: 50px; height: 50px; border-radius: 50%; background: linear-gradient(135deg, #3b82f6, #1e3a8a); display: flex; align-items: center; justify-content: center; color: white; font-size: 20px; font-weight: bold; }
        .character-details h2 { color: #1e3a8a; font-size: 18px; margin-bottom: 4px; }
        .character-status { display: flex; align-items: center; gap: 8px; font-size: 12px; color: #6b7280; }
        .status-dot { width: 8px; height: 8px; border-radius: 50%; background: #10b981; animation: pulse 2s infinite; }
        @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
        .header-actions { display: flex; gap: 10px; }
        .header-btn { padding: 8px 16px; border: none; border-radius: 20px; background: #f8fafc; color: #1e3a8a; cursor: pointer; font-size: 14px; transition: all 0.3s ease; }
        .header-btn.primary { background: #f59e0b; color: white; }
        .chat-container { flex: 1; display: grid; grid-template-columns: 250px 1fr 300px; gap: 0; overflow: hidden; }
        .chat-history { background: white; border-right: 1px solid #e5e7eb; overflow-y: auto; padding: 20px; }
        .history-title { font-size: 16px; font-weight: bold; color: #1e3a8a; margin-bottom: 15px; }
        .history-item { padding: 10px; border-radius: 10px; margin-bottom: 8px; cursor: pointer; transition: all 0.3s ease; border: 1px solid transparent; }
        .history-item:hover { background: #f8fafc; border-color: #e5e7eb; }
        .history-item.active { background: #dbeafe; border-color: #3b82f6; }
        .chat-messages { display: flex; flex-direction: column; overflow-y: auto; padding: 20px; gap: 15px; }
        .message { display: flex; gap: 10px; max-width: 80%; }
        .message.user { align-self: flex-end; flex-direction: row-reverse; }
        .message-avatar { width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-size: 16px; font-weight: bold; flex-shrink: 0; }
        .message.user .message-avatar { background: linear-gradient(135deg, #3b82f6, #1d4ed8); }
        .message.ai .message-avatar { background: linear-gradient(135deg, #6b7280, #4b5563); }
        .message-content { background: white; padding: 12px 16px; border-radius: 18px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); position: relative; }
        .message.user .message-content { background: linear-gradient(135deg, #3b82f6, #1d4ed8); color: white; }
        .message-text { font-size: 14px; line-height: 1.5; margin-bottom: 8px; }
        .message-time { font-size: 11px; color: #9ca3af; }
        .message.user .message-time { color: rgba(255, 255, 255, 0.7); }
        .typing-indicator { display: none; align-items: center; gap: 10px; padding: 10px 0; }
        .typing-dots { display: flex; gap: 4px; }
        .typing-dot { width: 8px; height: 8px; border-radius: 50%; background: #9ca3af; animation: typing 1.4s infinite; }
        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }
        @keyframes typing { 0%, 60%, 100% { transform: translateY(0);} 30% { transform: translateY(-10px);} }
        .character-panel { background: white; border-left: 1px solid #e5e7eb; padding: 20px; overflow-y: auto; }
        .chat-input { background: white; border-top: 1px solid #e5e7eb; padding: 20px; display: flex; gap: 10px; align-items: flex-end; }
        .input-container { flex: 1; position: relative; }
        .message-input { width: 100%; min-height: 40px; max-height: 120px; padding: 10px 50px 10px 16px; border: 2px solid #e5e7eb; border-radius: 20px; font-size: 14px; resize: none; outline: none; transition: all 0.3s ease; }
        .message-input:focus { border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); }
        .send-btn { background: #3b82f6; color: white; border: none; border-radius: 50%; width: 50px; height: 50px; cursor: pointer; font-size: 16px; transition: all 0.3s ease; display: flex; align-items: center; justify-content: center; }
        .send-btn:disabled { background: #9ca3af; cursor: not-allowed; }
        @media (max-width: 1024px) { .chat-container { grid-template-columns: 200px 1fr; } .character-panel { display: none; } }
        @media (max-width: 768px) { .chat-container { grid-template-columns: 1fr; } .chat-history { display: none; } .message { max-width: 90%; } .chat-header { padding: 10px 15px; } }
    </style>
    <script src="/js/api.js"></script>
    <script src="/js/auth.js"></script>
</head>
<body>
    <header class="chat-header">
        <div class="character-info">
            <div class="character-avatar" id="characterAvatar">角</div>
            <div class="character-details">
                <h2 id="characterName">角色</h2>
                <div class="character-status"><div class="status-dot"></div><span>在线</span></div>
            </div>
        </div>
        <div class="header-actions">
            <button class="header-btn" onclick="location.href='/character-selection.html'">角色</button>
            <button class="header-btn primary" onclick="location.href='/user-settings.html'">设置</button>
            <button class="header-btn" onclick="Auth.logout()">退出</button>
        </div>
    </header>

    <div class="chat-container">
        <aside class="chat-history">
            <h3 class="history-title">对话历史</h3>
            <div id="historyList"></div>
        </aside>

        <main class="chat-messages" id="chatMessages">
            <div class="typing-indicator" id="typingIndicator">
                <div class="message-avatar">AI</div>
                <div class="typing-dots"><div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div></div>
            </div>
        </main>

        <aside class="character-panel">
            <h3 class="history-title">角色信息</h3>
            <div id="characterBackground" style="font-size:12px;color:#6b7280;line-height:1.5"></div>
            <div style="margin-top:12px"><strong>技能标签</strong>
                <div id="characterTags" style="display:flex;flex-wrap:wrap;gap:6px;margin-top:6px"></div>
            </div>
        </aside>
    </div>

    <div class="chat-input">
        <div class="input-container">
            <textarea class="message-input" id="messageInput" placeholder="输入消息..." rows="1"></textarea>
        </div>
        <button class="send-btn" id="sendBtn" title="发送">➤</button>
    </div>

    <script>
      Auth.requireAuth();
      const params = new URLSearchParams(location.search);
      let conversationId = params.get('conversationId');
      const characterId = params.get('characterId');
      const chatMessages = document.getElementById('chatMessages');
      const messageInput = document.getElementById('messageInput');
      const sendBtn = document.getElementById('sendBtn');
      const typingIndicator = document.getElementById('typingIndicator');

      function addMessage(text, sender, returnElement = false) {
        const wrapper = document.createElement('div');
        wrapper.className = `message ${sender}`;
        const avatar = sender === 'user' ? '你' : 'AI';
        const time = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        wrapper.innerHTML = `<div class="message-avatar">${avatar}</div><div class="message-content"><div class="message-text">${text}</div><div class="message-time">${time}</div></div>`;
        chatMessages.appendChild(wrapper);
        chatMessages.scrollTop = chatMessages.scrollHeight;
        
        if (returnElement) {
          return wrapper;
        }
      }

      function showTyping(show) { typingIndicator.style.display = show ? 'flex' : 'none'; }
      
      function scrollToBottom() {
        chatMessages.scrollTop = chatMessages.scrollHeight;
      }

      async function ensureConversation() {
        if (conversationId) return conversationId;
        // 延迟创建对话，只有在用户发送消息时才创建
        return null;
      }

      async function loadConversation() {
        if (!conversationId) return;
        const data = await ConversationsApi.messages(conversationId, 1, 50);
        const list = data.list || data.records || [];
        chatMessages.innerHTML = '';
        list.forEach(m => addMessage(m.content, m.sender === 'USER' ? 'user' : 'ai'));
      }

      async function loadCharacter() {
        if (!characterId) return;
        const c = await CharactersApi.get(characterId);
        document.getElementById('characterName').textContent = c.name;
        document.getElementById('characterAvatar').textContent = (c.name || '角')[0];
        document.getElementById('characterBackground').textContent = c.background || c.description || '';
        const tags = [];
        if (c.category) tags.push(c.category); if (c.era) tags.push(c.era); if (c.region) tags.push(c.region); if (c.language) tags.push(c.language);
        document.getElementById('characterTags').innerHTML = tags.map(t => `<span class="character-tag" style="padding:4px 8px;background:#fef3c7;color:#92400e;border-radius:12px;font-size:11px">${t}</span>`).join('');
      }

      async function loadHistory() {
        const historyList = document.getElementById('historyList');
        historyList.innerHTML = '';
        try {
          // 传递当前角色ID，只加载该角色的对话历史
          const data = await ConversationsApi.list(1, 50, characterId);
          const list = data.list || [];
          list.forEach(h => {
            const item = document.createElement('div');
            item.className = 'history-item';
            if (h.id == conversationId || h.conversationId == conversationId) {
              item.classList.add('active');
            }
            const ch = (h.title || '会话').slice(0,1);
            const time = h.lastMessageAt ? new Date(h.lastMessageAt).toLocaleString() : '';
            item.innerHTML = `<div class="history-avatar" style="width:30px;height:30px;border-radius:50%;background:linear-gradient(135deg,#3b82f6,#1e3a8a);display:flex;align-items:center;justify-content:center;color:white;font-size:12px;font-weight:bold;margin-right:10px">${ch}</div><div class="history-info" style="flex:1"><div class="history-character" style="font-size:14px;color:#1e3a8a;margin-bottom:2px">${h.title || '会话'}</div><div class="history-time" style="font-size:11px;color:#6b7280">${time}</div></div>`;
            item.addEventListener('click', () => {
              location.href = `/chat.html?conversationId=${h.id || h.conversationId}&characterId=${h.characterId || characterId}`;
            });
            historyList.appendChild(item);
          });
        } catch (error) {
          console.error('加载对话历史失败:', error);
          historyList.innerHTML = '<div style="color:#6b7280;font-size:12px;text-align:center;padding:20px">加载对话历史失败</div>';
        }
      }

      messageInput.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = Math.min(this.scrollHeight, 120) + 'px';
        sendBtn.disabled = !this.value.trim();
      });

      async function sendMessage() {
        const text = messageInput.value.trim();
        if (!text) return;
        
        // 如果没有对话ID，先创建对话
        if (!conversationId) {
          try {
            const created = await ConversationsApi.create({ characterId: Number(characterId) });
            conversationId = created.id || created.conversationId;
            // 创建对话后重新加载历史记录
            await loadHistory();
          } catch (error) {
            console.error('创建对话失败:', error);
            alert('创建对话失败，请重试');
            return;
          }
        }
        
        addMessage(text, 'user');
        messageInput.value = ''; messageInput.style.height = 'auto'; sendBtn.disabled = true;
        
        // 创建AI消息容器，用于流式显示
        const aiMessageElement = addMessage('', 'ai', true);
        const messageTextElement = aiMessageElement.querySelector('.message-text');
        
        showTyping(true);
        
        try {
          console.log('开始调用普通API，对话ID:', conversationId, '内容:', text);
          
          // 直接使用普通API
          const reply = await ConversationsApi.sendMessage(conversationId, text);
          console.log('API回复:', reply);
          
          // 从API响应中提取内容
          let content = '';
          if (reply && reply.content) {
            content = reply.content;
          } else {
            content = '抱歉，我暂时无法回复您的消息。';
          }
          console.log('提取内容:', content);
          
          messageTextElement.textContent = content;
          showTyping(false);
          scrollToBottom();
          
        } catch (err) {
          showTyping(false);
          messageTextElement.textContent = '出错了：' + (err.message || 'AI回复失败');
        }
      }

      sendBtn.addEventListener('click', sendMessage);
      messageInput.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }});

      (async function init(){
        try {
          await Promise.all([loadCharacter(), loadConversation(), loadHistory()]);
        } catch (e) { console.error(e); }
      })();
    </script>
</body>
</html>


